package com.dindang.propertyfee.mvp.presenter;

import android.app.Application;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.dindang.propertyfee.R;
import com.dindang.propertyfee.app.AppConst;
import com.dindang.propertyfee.mvp.contract.OwnerSearchContract;
import com.dindang.propertyfee.mvp.model.entity.BaseResponse;
import com.dindang.propertyfee.mvp.model.entity.PropertyCharge;
import com.dindang.propertyfee.mvp.ui.adapter.custom.OwnerSearchViewAdapter;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.longxi.gamer_base.utils.SharedPreferencesUtils;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import in.srain.cube.views.ptr2.PtrDefaultHandler2;
import in.srain.cube.views.ptr2.PtrFrameLayout;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class OwnerSearchPresenter extends BasePresenter<OwnerSearchContract.Model, OwnerSearchContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private List<String> mHistory = new ArrayList<>();

    private List<PropertyCharge.RecentBill.Rows> mSearchResult = new ArrayList<>();
    private OwnerSearchViewAdapter mAdapter;
    private InputMethodManager mImm;
    private String HISTORY_SP_KEY = "OWNERSEARCH";
    private int LIMIT = 10;
    private PropertyCharge.RecentBillParam mParam = new PropertyCharge.RecentBillParam(LIMIT);

    @Inject
    public OwnerSearchPresenter(OwnerSearchContract.Model model, OwnerSearchContract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        initView();
        initListener();
        setHistoryData();
    }

    private void initView() {
        mAdapter = new OwnerSearchViewAdapter(mSearchResult, new OwnerSearchViewAdapter.OnOwnerSearchListener() {
            @Override
            public void onClick(int position) {
                PropertyCharge.RecentBill.Rows rows = mSearchResult.get(position);
                ARouter.getInstance().build("/propertyfee/activity/ReceivableDetailActivity")
                        .withString(AppConst.ID, rows.c_nodedate_id)
                        .withString(AppConst.RECEIVABLEDETAIL_ADDRESS, rows.bName + "/" + rows.addr)
                        .withString(AppConst.RECEIVABLEDETAIL_NAME_TEL, rows.custName + "/" + rows.c_telphone)
                        .navigation();
            }
        });
        mRootView.getRecyclerview().setAdapter(mAdapter);
        mImm = (InputMethodManager) mRootView.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    private void initListener() {
        mRootView.getEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //回车时返回true拦截事件，不让换行
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String keyword = mRootView.getEditText().getText().toString().trim();
                    if (TextUtils.isEmpty(keyword)) {
                        ArmsUtils.snackbarText("请输入搜索内容");
                    } else {//不为空时才添加标签
                        toSearch(keyword);
                        saveKeyword2Sp(keyword);
                        mImm.hideSoftInputFromWindow(mRootView.getEditText().getWindowToken(), 0);
                    }
                    return true;
                }
                return false;
            }
        });

        mRootView.getEditText().addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() > 0){
                    String keyword = mRootView.getEditText().getText().toString().trim();
                    if(!TextUtils.isEmpty(keyword)){
                        toSearch(keyword);
                    }
                }else{
                    setHistoryData();
                }
            }
        });

        mRootView.getTvClearSearchRecord().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferencesUtils.clear(mApplication, HISTORY_SP_KEY);
                setHistoryData();
            }
        });

        mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.BOTH);
        mRootView.getPtrclassicframelayout().disableWhenHorizontalMove(true);
        mRootView.getPtrclassicframelayout().setLastUpdateTimeRelateObject(this);
        mRootView.getPtrclassicframelayout().setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                queryRecentBill();
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mParam.page = 0;
                queryRecentBill();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return super.checkCanDoRefresh(frame, content, header);
            }

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return super.checkCanDoLoadMore(frame, content, footer);
            }
        });
    }

    private void toSearch(String keyword){
        mParam.likeValue = keyword;
        mParam.page = 0;

        mRootView.getGroupHistory().setVisibility(View.GONE);
        mRootView.getRecyclerview().setVisibility(View.VISIBLE);

        mAdapter.setKeyword(keyword);

        mRootView.getFramelayout().setVisibility(View.VISIBLE);
        queryRecentBill();
    }

    /**
     * 历史搜索记录设置
     */
    public void setHistoryData(){
        mHistory.clear();
        String historyKeyword = SharedPreferencesUtils.getParam(mApplication, HISTORY_SP_KEY, "").toString();
        if(!TextUtils.isEmpty(historyKeyword)){
            mHistory = JSON.parseArray(historyKeyword, String.class);
        }

        //判断是否有历史搜索记录数据
        if(mHistory.size() > 0){
            mRootView.getGroupHistory().setVisibility(View.VISIBLE);
            mRootView.getRecyclerview().setVisibility(View.GONE);
            mRootView.getFramelayout().setVisibility(View.GONE);
        }else{
            mRootView.getGroupHistory().setVisibility(View.GONE);
            mRootView.getRecyclerview().setVisibility(View.GONE);
            mRootView.getFramelayout().setVisibility(View.VISIBLE);
            mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_ENTER_KEYWORD);
            return;
        }

        //往容器内添加TextView数据
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, 20, 20, 0);
        if (mRootView.getFlowLayout() != null) {
            mRootView.getFlowLayout().removeAllViews();
        }
        for (int i = 0; i < mHistory.size(); i++) {
            String keyword = mHistory.get(i);
            TextView tv = new TextView(mRootView.getActivity());
            tv.setPadding(28, 10, 28, 10);
            tv.setText(mHistory.get(i));
            tv.setMaxEms(15);
            tv.setEllipsize(TextUtils.TruncateAt.END);
            tv.setSingleLine();
            tv.setTextColor(mRootView.getActivity().getResources().getColor(R.color.color_text8));
            tv.setBackgroundResource(R.drawable.bg_border);
            tv.setLayoutParams(layoutParams);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mRootView.getEditText().setText(keyword);
                    saveKeyword2Sp(keyword);
                }
            });
            mRootView.getFlowLayout().addView(tv, layoutParams);
        }
    }

    /**
     * 取消按钮
     */
    public void toCancle() {
        mImm.hideSoftInputFromWindow(mRootView.getEditText().getWindowToken(), 0);
        if ("".equals(mRootView.getEditText().getText().toString().trim())) {
            mRootView.getActivity().finish();
        }else{
            mRootView.getEditText().setText("");
            mRootView.getFramelayout().setVisibility(View.GONE);
        }
    }

    /**
     * 将搜索数据存到sp中
     * @param keyword
     * @return
     */
    public void saveKeyword2Sp(String keyword){
        if(mHistory.contains(keyword)){
            mHistory.remove(keyword);
            mHistory.add(0, keyword);
        }else{
            if(mHistory.size() >= 10){
                mHistory.remove(mHistory.size() - 1);
            }
            mHistory.add(0, keyword);
        }
        String json = JSON.toJSONString(mHistory);
        SharedPreferencesUtils.setParam(mApplication, HISTORY_SP_KEY, json);
    }

    /**
     * 条件搜索
     */
    private void queryRecentBill(){
        mParam.corpid = BaseAppConst.accountInfo.getCorpId();
        mModel.queryRecentBill(mParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {

        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<PropertyCharge.RecentBill>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<PropertyCharge.RecentBill> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                if(!response.isSuccess()){
                    ArmsUtils.makeText(mApplication, response.getStatuMsg());
                    return;
                }
                mSearchResult.addAll(response.getData().pageData.rows);

                if(mRootView.getPtrclassicframelayout().isRefreshing()){
                    mRootView.getPtrclassicframelayout().refreshComplete();
                }
                if(response.getData().pageData.rows.size() < LIMIT){
                    mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.REFRESH);
                }else{
                    mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.BOTH);
                    mParam.page++;
                }

                if(mParam.page == 0){
                    mSearchResult.clear();
                }
                mSearchResult.addAll(response.getData().pageData.rows);
                if(mSearchResult.size() == 0){
                    mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_NO_DATA);
                }else{
                    mRootView.getEmptyLayout().hide();
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
                mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_ERROR);
                if(mRootView.getPtrclassicframelayout().isRefreshing()){
                    mRootView.getPtrclassicframelayout().refreshComplete();
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mHistory = null;
        this.mParam = null;
        this.mSearchResult = null;
        this.mAdapter = null;
        this.mImm = null;
    }
}
